/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.mvc.helpers
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	[Event(name="started", type="com.toritoriworks.utils.HelperEvent")]
	[Event(name="stopped", type="com.toritoriworks.utils.HelperEvent")]
	[Event(name="skipped", type="com.toritoriworks.utils.HelperEvent")]
	[Event(name="canceled", type="com.toritoriworks.utils.HelperEvent")]
	[Event(name="resumed", type="com.toritoriworks.utils.HelperEvent")]
	[Event(name="done", type="com.toritoriworks.utils.HelperEvent")]

	internal class Context extends EventDispatcher implements IContextHandler {
		private static var _handlers:Array = new Array();
		private var _before:Function;
		private var _after:Function;
		protected const DONE:HelperEvent = new HelperEvent(HelperEvent.DONE);
		public function Context()	{			
		}
		
		protected function setup(before:Function,after:Function):void {
			_handlers.push(this);
			addEventListener(HelperEvent.DONE, wrappingHandler);
			addEventListener(HelperEvent.CANCELED, wrappingHandler);
			addEventListener(HelperEvent.SKIPPED, wrappingHandler);
			_before = before;
			_after = after;
			this.before();
		}
		
		protected static function get handlers():Array {
			return _handlers;
		}
		
		private function wrappingHandler(event:Event):void {
			var index:int = _handlers.indexOf(event.currentTarget);
			removeEventListener(HelperEvent.DONE, wrappingHandler);
			removeEventListener(HelperEvent.CANCELED, wrappingHandler);
			removeEventListener(HelperEvent.SKIPPED, wrappingHandler);
			_handlers.splice(index,1);
			cleanUp();
//			trace("Helper=",_handlers.length);
		}
		
		protected function cleanUp():void {
			_after = null;
			_before = null;
		}
		
		public function start():void {
		}
		
		public function resume():void {
		}
		
		public function stop():void {
		}
		
		public function before():void {
			invoke(_before);
		}

		public function after():void {
			invoke(_after);
		}
		
		public function wrapUp():void {
			stop();
			after();
		}
		
		public function dispatch(event:HelperEvent):void {
			dispatchEvent(event);
		}

		private function invoke(fnc:Function):void {
			if (fnc != null) {
				fnc();
			}
		}
		
	}
}